package com.fanwei.rocketmq.service.impl;

import com.alibaba.fastjson.JSON;
import com.fanwei.rocketmq.domain.Test;
import com.fanwei.rocketmq.service.MQTXProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * @desc : 事务消息demo
 * @author fanwei
 */
@Slf4j
@Service("mQTXProducerServiceImpl")
public class MQTXProducerServiceImpl implements MQTXProducerService {

    private static final String Topic = "RLT_TEST_TOPIC";
    private static final String Tag = "charge";
    private static final String Tx_Charge_Group = "Tx_Charge_Group";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 先向MQ Server发送半消息
     * @param test
     */
    @Override
    public TransactionSendResult sendHalfMsg(Test test) {
        log.info("【发送半消息】uuid={}", test.getUuid());
        Message<Test> message = MessageBuilder.withPayload(test).build();
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(
                Tx_Charge_Group + "_"+Topic + ":" + Tag,
                message,
                test);
        log.info("【发送半消息】sendResult={}", JSON.toJSONString(sendResult));
        return sendResult;
    }
}
